<template>
	<div>
		<div class="searchhistory" v-if="searchHistory[0]">

			<div class="title">
				<van-icon name="underway-o" color="#B0352F" />
				历史搜索
				<span @click="empty">清空历史记录</span>
			</div>


			<van-tag v-for="(item,index) in searchHistory" :key="index" closeable size="large" @click='search(item)'
				@close="close(item)">
				{{ item }}
			</van-tag>

		</div>
		<HotSearch></HotSearch>
	</div>
</template>

<script>
	
	import {mapActions} from 'vuex'
	import HotSearch from '@/components/Search/HotSearch'
	import { Dialog } from 'vant';
	
	export default {
		name: 'SearchHistory',
		components:{HotSearch},
		data() {
			return {
				show: true,
				searchHistory: []
			};
		},
		methods: {
			close(item) {
				const value = this.searchHistory.indexOf(item);
				this.searchHistory.splice(value, 1);
				//存入本地浏览器缓存
				window.localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
			},

			//清空搜索历史
			empty() {
				
				Dialog.confirm({
				  message: '确认清除全部历史记录吗？',
				})
				  .then(() => {
				    // on confirm
					this.searchHistory = []
					//存入本地浏览器缓存
					window.localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
				  })
				  .catch(() => {
				    // on cancel
				  });
				
			},
			...mapActions('commodityList',['searchList']),
			search(item) {
				this.searchList(item)
				this.$router.push({
					name: 'searchList',
					query: {
						value: item
					}
				})
			}

		},
		created() {

			//判读本地储存里是否有搜索记录，true将搜索记录存入数组
			if (!!localStorage.getItem('searchHistory')) {
				this.searchHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];
			}

		}
	}
</script>

<style scoped>
	.searchhistory {
		margin: 0.625rem 1.25rem;
	}

	.title {
		margin-bottom: 1.25rem;
		color: #333333;
	}

	.title span {
		margin-left: 8.75rem;
	}

	.van-tag {
		margin: 5px;
	}
</style>
